var express = require('express');
var router = express.Router();
var multiparty = require("multiparty");
var mergeDir = require('./../public/javascripts/copyDir')

// 设置允许跨域访问该服务.
router.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  //Access-Control-Allow-Headers ,可根据浏览器的F12查看,把对应的粘贴在这里就行
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Methods', '*');
  // res.header('Content-Type', 'application/json;charset=utf-8');
  // res.header("Content-Type", "application/x-www-form-urlencoded");
  next();
});

/* GET home page. */
router.get('/', function (req, res, next) {
  res.type('html');
  res.render('index');
});

/**
 * get方法请求
 */
router.get('/copdir', function (req, res, next) {
  console.log('请求参数', req.query)
  res.send({
    code: 200,
    data: req.query
  })
});

/**
 * post传数组 json格式
 */
router.post('/json', function (req, res, next) {
  console.log('json格式请求参数', req.body)
  res.send({
    code: 200,
    msg: 'json格式返回数据'
  })
  // mergeDir(req.body.dirPathArr, req.body.mergePath, function (data) {
  //   res.send(data)
  // })
});
/**
 * post 传formData数据格式
 */
router.post('/formData', function (req, res, next) {
  console.log('formData数据格式请求参数', req.body)
  let form = new multiparty.Form()
  form.parse(req, (err, fields, file) => {
    console.log(err, fields, file)
    console.log(fields.test + '')
    console.log(JSON.parse(fields.dirPathArr).length)
    res.send({
      code: 200,
      msg: 'formData格式返回数据'
    })
  })
  // mergeDir(req.body.dirPathArr, req.body.mergePath, function (data) {
  //   res.send(data)
  // })
});


// 定制 404 页面 (返回404状态码)
router.use(function (req, res) {
  let currentTime = new Date();
  res.type('text/plain');
  res.status(404);
  res.send('404 - 你访问的页面可能去了火星\n' + currentTime);
});


//定制 500 页面 (返回500状态码)
router.use(function (err, req, res, next) {
  let currentTime = new Date();
  let errInfo = err.stack;
  res.type('text/plain');
  res.status(500);
  res.send('500 - 服务器发生错误\n' + 'errInfo:' + errInfo + '\n' + 'currentTime:' + currentTime);
});




module.exports = router;